package com.ebeitech.doorapp.view;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.constants.CommonConstants;
import com.ebeitech.doorapp.domain.EMessage;
import com.ebeitech.doorapp.domain.dao.EMessageDao;
import com.ebeitech.doorapp.util.PublicUtil;
import com.ebeitech.library.constant.MessageConstants;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.ui.CommonTitleBar;
import com.ebeitech.library.ui.dialog.CommonAlertDialogFragment;
import com.ebeitech.library.ui.pulltorefresh.PullToRefreshBase;
import com.ebeitech.library.ui.pulltorefresh.PullToRefreshListView;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.TimeUtil;
import com.ebeitech.library.util.ViewUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by alice on 2018/6/11.
 */

public class MessageActivity extends BaseActivity {

	@BindView(R.id.view_title)
	CommonTitleBar mTitleBarView;
	@BindView(R.id.listView)
	PullToRefreshListView mPullToRefreshView;
	ListView mListView;

	private Context mContext;
	private BaseAdapter mAdapter;
	private List<EMessage> messageList = new ArrayList<EMessage>();
	private EMessageDao mMessageDao;
	private boolean isChange;
	private int mCurrentPage;
	private int mLastPage;
	private boolean isRefreshing;

	private String mTypeId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ebei_activity_pulltorefreshlistview);
		ButterKnife.bind(this);
		mContext = this;
		mMessageDao = EMessageDao.getInstance();
		Intent intent = getIntent();
		if (intent != null) {
			mTypeId = intent.getStringExtra(MessageConstants.MESSAGE_TYPE_ID);
		}
		initView();
		registerBroadCast();

		isChange = mMessageDao.setMessageReadByType(mTypeId) > -1;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver);
	}

	@Override
	public void finish() {
		if (isChange) {
			Intent intent = new Intent(MessageConstants.ACTION_MESSAGE_COUNT_CHANGE);
			sendBroadcast(intent);
			setResult(RESULT_OK);
		}
		super.finish();
	}

	private void initView() {
		mTitleBarView.setTitle(getString(R.string.ebei_message));

		mAdapter = new MessageAdapter();
		mListView = mPullToRefreshView.getRefreshableView();
		mPullToRefreshView.setScrollLoadEnabled(true);
		mPullToRefreshView.setPullRefreshEnabled(true);
		mPullToRefreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				if (!isRefreshing) {
					isRefreshing = true;
					mCurrentPage = 1;
					mLastPage = -1;
					loadMessage();
				} else {
					mPullToRefreshView.onPullDownRefreshComplete();
				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
				if (mCurrentPage != mLastPage) {
					if (!isRefreshing) {
						isRefreshing = true;
						mCurrentPage++;
						loadMessage();
					}
				} else {
					mPullToRefreshView.onPullUpRefreshComplete();
					Toast.makeText(mContext, R.string.ebei_pull_to_refresh_to_end, Toast.LENGTH_SHORT).show();
				}
			}
		});
		mListView.setAdapter(mAdapter);
		mListView.setDivider(null);

		mPullToRefreshView.doPullRefreshing(true, 300);
	}

	private void registerBroadCast() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(MessageConstants.ACTION_MESSAGE_RECEIVE);
		registerReceiver(mBroadcastReceiver, myIntentFilter);
	}

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (MessageConstants.ACTION_MESSAGE_RECEIVE.equals(action)) {
				EMessage message = (EMessage) intent.getSerializableExtra(MessageConstants.MESSAGE);
				if (message != null) {
					int index = messageList.indexOf(message);
					if (index > -1) {
						messageList.set(index, message);
					} else {
						messageList.add(0, message);
					}
					mAdapter.notifyDataSetChanged();
				}
			}
		}
	};

	private void loadMessage() {
		final CommonAlertDialogFragment mProgressDialog = ViewUtil.showProgressDialog(mContext);
		new AsyncTask<Void, Void, Void>() {

			private List<EMessage> messageListT = new ArrayList<EMessage>();

			@Override
			protected Void doInBackground(Void... voids) {
				messageListT = mMessageDao.getMessageListWithPage(mTypeId, mCurrentPage, CommonConstants.PAGE_SIZE);
				return null;
			}

			@Override
			protected void onPostExecute(Void aVoid) {
				super.onPostExecute(aVoid);
				messageList.clear();
				messageList.addAll(messageListT);
				if (!isFinishing()) {
					ViewUtil.dismissDialog(mProgressDialog);
				}
				if (mCurrentPage == 1) {
					messageList.clear();
				}
				if (messageListT != null && messageListT.size() > 0) {
					messageList.addAll(messageListT);
					if (messageListT.size() < CommonConstants.PAGE_SIZE) {
						mLastPage = mCurrentPage;
					}
				} else {
					mLastPage = mCurrentPage;
				}
				mAdapter.notifyDataSetChanged();
				mPullToRefreshView.onPullDownRefreshComplete();
				mPullToRefreshView.onPullUpRefreshComplete();
				isRefreshing = false;
			}
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	class MessageAdapter extends BaseAdapter {

		private float imageWidth;
		private float maxWidth;
		private float imageMargin;

		public MessageAdapter() {
			imageWidth = ViewUtil.dp2px(mContext, 55);
		}

		@Override
		public int getCount() {
			return messageList.size();
		}

		@Override
		public Object getItem(int position) {
			return messageList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder mViewHolder = null;
			if (convertView == null) {
				convertView = LayoutInflater.from(mContext).inflate(R.layout.ebei_view_list_message_item, null);
				mViewHolder = new ViewHolder();
				mViewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
				mViewHolder.tvMsg = (TextView) convertView.findViewById(R.id.tvMsg);
				mViewHolder.tvTime = (TextView) convertView.findViewById(R.id.tvTime);
				mViewHolder.detailView = convertView.findViewById(R.id.view_detail);
				convertView.setTag(mViewHolder);
			} else {
				mViewHolder = (ViewHolder) convertView.getTag();
			}

			EMessage message = (EMessage) getItem(position);
			mViewHolder.tvTitle.setText(message.getFromName());
			String time = message.getTime();
			if (!StringUtil.isStringNullOrEmpty(time)) {
				time = com.ebeitech.doorapp.qqim.util.TimeUtil.getChatTimeStrWithTimeMillis(TimeUtil.getTimeMillis(time));
			} else {
				time = "";
			}
			mViewHolder.tvTime.setText(time);
			mViewHolder.tvMsg.setText(message.getContent());

			final String invokeUrl = message.getInvokeUrl();
			if (StringUtil.isStringNullOrEmpty(invokeUrl)) {
				mViewHolder.detailView.setVisibility(View.GONE);
			} else {
				mViewHolder.detailView.setVisibility(View.VISIBLE);
			}

			convertView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (StringUtil.isStringNullOrEmpty(invokeUrl)) {
						return;
					}

					String url = null;
					if (invokeUrl.contains("http://") || invokeUrl.contains("https://")) {
						url = invokeUrl;
					} else if (EMessage.MESSAGE_TYPE_APP.equals(message.getMessageType())) {
						url = "file:///" + PublicUtil.getAppFile(mContext) + File.separator + "index.html#/" + invokeUrl;
						SPManager.getInstance(mContext).put(SPConstants.APP_ID, message.getFromId());
					}

					Intent intent = new Intent(mContext, CordovaBaseActivity.class);
					intent.putExtra("url", url);
					startActivity(intent);
				}
			});
			return convertView;
		}

		class ViewHolder {
			TextView tvTitle;
			TextView tvMsg;
			TextView tvTime;
			View detailView;
		}
	}

}
